package com.gomoku.botrunning.service.impl.utils;

import com.alibaba.fastjson2.JSONObject;
import org.joor.Reflect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.UUID;
import java.util.function.Supplier;

@Component
public class Consumer extends Thread{
    private Bot bot;
    private final static String receiveBotMoveUrl = "http://127.0.0.1:3000/pk/receivebotmove/";
    private static RestTemplate restTemplate;
    @Autowired
    private void setRestTemplate(RestTemplate restTemplate) {
        Consumer.restTemplate = restTemplate;
    }
    public void startTimeout(long timeout, Bot bot){
        this.bot = bot;
        this.start(); //会执行botCode代码，返回结果

        try {
            this.join(timeout); //用线程来控制执行时间 最多等待timeout秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            this.interrupt(); //终止当前线程
        }
    }

    private String addUid(String code,String uid){ //在code 中的Bot类名后添加uid
        int k = code.indexOf(" implements java.util.function.Supplier<JSONObject>");
        return code.substring(0, k)+ uid+ code.substring(k);
    }
    @Override
    public void run(){

        UUID uuid = UUID.randomUUID();
        String uid = uuid.toString().substring(0,8);

        //Supplier是Java自带的一个,可调用的接口
        //通过反射create创建该类的实例botInterface，并将其包装为 Supplier<Integer> 接口（即可以通过 botInterface.get() 获取计算结果）。
        Supplier<JSONObject> botInterface = Reflect.compile(
                "com.gomoku.botrunning.utils.Bot" + uid,
                addUid(bot.getBotCode(), uid)
        ).create().get();

        //写入本地文件input.txt,botInterface代码执行时从input.txt文件读取输入（而非直接传参）,
        File file = new  File("input.txt");
        try (PrintWriter out = new PrintWriter(file) ) {
            out.println(bot.getInput()); // 将用户输入数据写入本地的input.txt，然后从本地input.txt获取
            out.flush(); // 确保数据立即写入磁盘
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        //文件写入之后，可以通过调用重写的get方法获取nextMove
        JSONObject direction = botInterface.get(); // 调用编译后的逻辑计算结果
        //System.out.println("botId: "+bot.getBotId()+"direction: "+direction);

        MultiValueMap<String,String> data = new LinkedMultiValueMap<>();
        data.add("userId",bot.getUserId().toString());
        data.add("botId",bot.getBotId().toString());
        data.add("direction", direction.toString());
        restTemplate.postForEntity(receiveBotMoveUrl, data, String.class);
    }
}
